﻿using Estsh.Core.Controllers;
using Estsh.Core.Model.Extend.Models;
using Estsh.Core.Model.Result;
using Estsh.Core.Models;
using Estsh.Core.Util;
using Estsh.Core.Wms.IServices;
using Microsoft.AspNetCore.Mvc;
using System.Collections;


namespace Estsh.Core.Web.Plugin.Wms.Controllers
{
    [Area("wms")]
    public class MovementManageController : BaseController
    {
        private IMovementManageService service;
        public MovementManageController(IMovementManageService _service)
        {
            service = _service;
        }
        //
        // GET: /Menu/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取移动单管理列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getMoveHeaderListByPage(string orderNo, string orderType, string orderStatus, string startTime, string endTime, Pager pager, String direction, String sort, string fedbatchType ,string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            result.Add("pager.pageNo", pager.pageNo);
            Hashtable dataHt = this.service.getMoveHeaderListByPage(orderNo, orderType, orderStatus, startTime, endTime, enabled, factoryId, pager, direction, sort,fedbatchType);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            result.Add("sort", sort);
            result.Add("direction", direction);
            return Json(result);
        }

        /// <summary>
        /// 获取移动单明细管理列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getMoveDetailListByPage(string orderNo, string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            Hashtable dataHt = this.service.getMoveDetailListByPage(orderNo, enabled, factoryId);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            return Json(result);
        }

        /// <summary>
        /// 获取移动单条码管理列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getMoveSnListByPage(string orderNo, string partNo, string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            Hashtable dataHt = this.service.getMoveSnListByPage(orderNo, partNo, enabled, factoryId);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            return Json(result);
        }

        /// <summary>
        /// 生成条码
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult onBarcodeGenerator(String orderNos)
        {
            Hashtable result = new Hashtable();
            try
            {
                result = this.service.onBarcodeGenerator(orderNos);
            }
            catch (Exception e)
            {
                result.Add("message", "生成条码失败，请重查看！");
                result.Add("flag", "error");
            }
            return Json(result);
        }

        public ActionResult getSelectMoveOrderType()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetMoveOrderType();
            result.Add("list", menuList);
            return Json(result);
        }

        public ActionResult getSelectFedbatchType()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetFedbatchType();
            result.Add("list", menuList);
            return Json(result);
        }

        public ActionResult getSelectFedbatchMethods()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetFedbatchMethods();
            result.Add("list", menuList);
            return Json(result);
        }

        public ActionResult getSelectZoneByZoneId(string zoneId)
        {
            Hashtable result = new Hashtable();
            List<SysZone> Zones = service.getSelectZone2(zoneId);
            return Json(Zones);
        }
        public ActionResult getSelectMoveOrderStatus()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetMoveOrderStatus();
            result.Add("list", menuList);
            return Json(result);
        }
        /// <summary>
        /// 获取父节点菜单下拉列表数据
        /// </summary>
        /// <rehuoturns></returns>
        public ActionResult getSelectFactory()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectFactory();
            result.Add("list", menuList);
            return Json(result);
        }
        public ActionResult getSelectWarehouse()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectWarehouse();
            result.Add("list", menuList);
            return Json(result);
        }

        public ActionResult getSelectZone()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectZone();
            result.Add("list", menuList);
            return Json(result);
        }


        /// <summary>
        /// 获取父节点菜单下拉列表数据
        /// </summary>
        /// <rehuoturns></returns>
        public ActionResult getSelectLocate(int zoneId)
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectLocate(zoneId);
            result.Add("list", menuList);
            return Json(result);
        }



        public ActionResult getSelectVendor()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectVendor();
            result.Add("list", menuList);
            return Json(result);
        }
        public ActionResult GetPart()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetPart();
            result.Add("list", menuList);
            return Json(result);
        }
        /// <summary>
        /// 保存菜单数据
        /// </summary>
        /// <returns></returns>
        public ActionResult saveMovementManage()
        {
            int fedbatchType = Request.Form["fedbatchType"] == "" ? 0 : int.Parse(Request.Form["fedbatchType"]);
            int fedbatchMethods = Request.Form["fedbatchMethods"] == "" ? 0 : int.Parse(Request.Form["fedbatchMethods"]);
            int orderType = int.Parse(Request.Form["orderType"]);
            int factoryId = CurrentEmp.FactoryId;
            String factoryCode = CurrentEmp.FactoryCode;
            String enabled = Request.Form["enabled"].ToString();

            string vendorId = Request.Form["vendorId"];
            string customerId = Request.Form["customerId"];
            String planDate = Request.Form["planDate"].ToString();
            String planTime = Request.Form["planTime"].ToString();
            String destWarehouseId = Request.Form["destWarehouseId"].ToString();
            String destZoneId = Request.Form["destZoneId"].ToString();
            String destErpWarehouse = Request.Form["destErpWarehouse"].ToString();
            String srcWarehouseId = Request.Form["srcWarehouseId"].ToString();
            String srcZoneId = Request.Form["srcZoneId"].ToString();
            String srcErpWarehouse = Request.Form["srcErpWarehouse"].ToString();
            String remarks = Request.Form["remarks"].ToString();
            String reforderno = Request.Form["refOrderNo"].ToString();
            String srcLocateId = Request.Form["srcLocateId"].ToString();
            String destLocateId = Request.Form["destLocateId"].ToString();

            String destWarehouseName = "";
            List<SysWarehouse> destWare = service.getSelectWarehouse(destWarehouseId);
            if (destWare.Count > 0)
            {
                destWarehouseName = destWare[0].WarehouseName;
            }
            String srcWarehouseName = "";
            List<SysWarehouse> srcWare = service.getSelectWarehouse(srcWarehouseId);
            if (srcWare.Count > 0)
            {
                srcWarehouseName = srcWare[0].WarehouseName;
            }

            String destLocateName = "";
            List<SysLocate> destLocates = service.getSelectLocate2(destLocateId);
            if (destLocates.Count > 0)
            {
                destLocateName = destLocates[0].LocateName;
            }
            String srcLocateName = "";
            List<SysLocate> srcLocates = service.getSelectLocate2(srcLocateId);
            if (srcLocates.Count > 0)
            {
                srcLocateName = srcLocates[0].LocateName;
            }

            String destZoneName = "";
            List<SysZone> destZones = service.getSelectZone(destZoneId);
            if (destZones.Count > 0)
            {
                destZoneName = destZones[0].ZoneName;
            }

            String srcZoneName = "";
            List<SysZone> srcZones = service.getSelectZone(srcZoneId);
            if (srcZones.Count > 0)
            {
                srcZoneName = srcZones[0].ZoneName;
            }

            WmsMoveHeader_Extend moveHeader = new WmsMoveHeader_Extend();
            moveHeader.prepareMaterial = fedbatchMethods;
            moveHeader.fedbatchType = fedbatchType;
            moveHeader.OrderType = orderType;
            moveHeader.FactoryId = factoryId;
            moveHeader.FactoryCode = factoryCode;
            moveHeader.Enabled = enabled;
            moveHeader.Remarks = remarks;
            moveHeader.RefOrderNo = reforderno;

            string detailRow = Request.Form["detailRow"].ToString();
            IList<WmsMoveDetail_Extend> moveDetailsList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WmsMoveDetail_Extend>>(detailRow);
            for (int i = 0; i < moveDetailsList.Count; i++)
            {
                moveDetailsList[i].ItemNo = (i + 1).ToString();
                //purchaseDetailList[i].PartId = Convert.ToInt32(PartId);
                string PartNo = string.IsNullOrEmpty(moveDetailsList[i].PartNo.ToString()) ? "0" : moveDetailsList[i].PartNo.ToString();
                List<SysPart> parts = service.GetPart(PartNo);
                if (parts.Count > 0)
                {
                    moveDetailsList[i].PartId = parts[0].PartId;
                    moveDetailsList[i].PartSpec = parts[0].PartSpec;
                    moveDetailsList[i].Unit = parts[0].Unit;
                }
                else
                {
                    moveDetailsList[i].PartId = 0;
                    moveDetailsList[i].PartSpec = "";
                    moveDetailsList[i].Unit = "";
                }
                //moveDetailsList[i].Qty = string.IsNullOrEmpty(Qty) ? 0 : Convert.ToDecimal(Qty);
                moveDetailsList[i].PickQty = 0;
                moveDetailsList[i].OutQty = 0;
                moveDetailsList[i].RecQty = 0;

                moveDetailsList[i].PlanDate = planDate;
                moveDetailsList[i].PlanTime = planTime;

                moveDetailsList[i].DestWarehouseId = string.IsNullOrEmpty(destWarehouseId) ? 0 : Convert.ToInt32(destWarehouseId);
                moveDetailsList[i].DestWarehouseName = destWarehouseName;
                moveDetailsList[i].DestZoneId = string.IsNullOrEmpty(destZoneId) ? 0 : Convert.ToInt32(destZoneId);
                moveDetailsList[i].DestZoneName = destZoneName;
                moveDetailsList[i].destLocateId = string.IsNullOrEmpty(destLocateId) ? "" : destLocateId;
                moveDetailsList[i].destLocateName = destLocateName;
                moveDetailsList[i].DestErpWarehouse = destErpWarehouse;

                moveDetailsList[i].SrcWarehouseId = string.IsNullOrEmpty(srcWarehouseId) ? 0 : Convert.ToInt32(srcWarehouseId);
                moveDetailsList[i].SrcWarehouseName = srcWarehouseName;
                moveDetailsList[i].SrcZoneId = string.IsNullOrEmpty(srcZoneId) ? 0 : Convert.ToInt32(srcZoneId);
                moveDetailsList[i].SrcZoneName = srcZoneName;
                moveDetailsList[i].srcLocateId = string.IsNullOrEmpty(srcLocateId) ? "" : srcLocateId;
                moveDetailsList[i].srcLocateName = srcLocateName;
                moveDetailsList[i].SrcErpWarehouse = srcErpWarehouse;

                moveDetailsList[i].Enabled = enabled;
                moveDetailsList[i].FactoryId = CurrentEmp.FactoryId;
                moveDetailsList[i].FactoryCode = CurrentEmp.FactoryCode;
                moveDetailsList[i].CreateUserId = CurrentEmp.EmpId;
            }

            String message = "";

            try
            {
                moveHeader.CreateUserId = CurrentEmp.EmpId;
                bool flag = this.service.saveMovementManage(moveHeader, moveDetailsList);
                if (flag == true)
                {
                    message = "添加成功";
                }
                else
                {
                    message = "添加失败！";
                }
            }
            catch (Exception e)
            {
                message = "添加失败！";
            }

            Hashtable result = new Hashtable();
            result.Add("message", message);
            return Json(result);
        }
        public ActionResult GetErpwarehouse()
        {
            Hashtable resault = new Hashtable();
            List<KeyValueResult> pdlineList = service.GetErpwarehouse();
            resault.Add("list", pdlineList);
            return Json(resault);
        }

        #region 过滤零件号
        public ActionResult GetPart_No(string q)
        {
            List<string> list = filePart(q);
            return writeResult(list);
        }

        /// <summary>
        /// 过滤零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<string> filePart(string key)
        {
            Hashtable autoComplateList = GetItemPart(key);
            List<String> result = new List<string>();
            foreach (System.Collections.DictionaryEntry item in autoComplateList)
            {
                if (item.Value.ToString().ToUpper().StartsWith(key.ToUpper()))
                {
                    result.Add(item.Value.ToString());
                }
            }
            return result;
        }
        /// <summary>
        /// 查询零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Hashtable GetItemPart(string key)
        {
            List<String> autoComplateList = new List<string>();
            Hashtable result = new Hashtable();

            try
            {
                List<SysPart> dt = service.GetPartNoInfo(key);
                for (int i = 0; i < dt.Count; i++)
                {
                    result.Add(dt[i].PartId.ToString(), dt[i].PartNo.ToString());

                }
            }
            catch (Exception e)
            {
                result = new Hashtable();
            }
            return result;
        }
        #endregion

        #region 过滤零件号简码
        public ActionResult GetPart_Spec(string q)
        {
            List<string> list = filePartSpec(q);
            return writeResult(list);
        }

        /// <summary>
        /// 过滤零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<string> filePartSpec(string key)
        {
            Hashtable autoComplateList = GetItemPartSpec(key);
            List<String> result = new List<string>();
            foreach (System.Collections.DictionaryEntry item in autoComplateList)
            {
                if (item.Value.ToString().ToUpper().StartsWith(key.ToUpper()))
                {
                    result.Add(item.Value.ToString());
                }
            }
            return result;
        }
        /// <summary>
        /// 查询零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Hashtable GetItemPartSpec(string key)
        {
            List<String> autoComplateList = new List<string>();
            Hashtable result = new Hashtable();

            try
            {
                List<SysPart> dt = service.GetPartSpecInfo(key);
                for (int i = 0; i < dt.Count; i++)
                {
                    result.Add(dt[i].PartId.ToString(), dt[i].PartSpec.ToString());
                }
            }
            catch (Exception e)
            {
                result = new Hashtable();
            }
            return result;
        }
        #endregion
        private ActionResult writeResult(List<string> list)
        {
            Hashtable result = new Hashtable();
            result.Add("list", list);
            return Json(result);
        }


        public ActionResult getPartNoInfo(string partNo)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartNoInfo(partNo);
            return Json(list);
        }
        public ActionResult getPartNoInfoByPartNo(string partNo)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartNoInfoByPartNo(partNo);
            return Json(list);
        }

        public ActionResult getPartSpecInfo(string partSpec)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartSpecInfo(partSpec);
            return Json(list);
        }
        public ActionResult getPartSpecInfoByPartSpec(string partSpec)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartSpecInfoByPartSpec(partSpec);
            return Json(list);
        }

        #region 关联单号

        public ActionResult GetWorkRefOrderNo(string refOrderNo, string orderType)
        {
            Hashtable resault = new Hashtable();
            List<MesWorkOrder> list = service.GetWorkRefOrderNo(refOrderNo,orderType);
            return Json(list);
        }


        public ActionResult GetRefOrderNo(string q)
        {
            List<string> list = fileRefOrderNo(q);
            return writeResult(list);
        }

        /// <summary>
        /// 过滤关联单号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<string> fileRefOrderNo(string key)
        {
            Hashtable autoComplateList = GetItemRefOrderNo(key);
            List<String> result = new List<string>();
            foreach (System.Collections.DictionaryEntry item in autoComplateList)
            {
                if (item.Value.ToString().ToUpper().StartsWith(key.ToUpper()))
                {
                    result.Add(item.Value.ToString());
                }
            }
            return result;
        }
        /// <summary>
        /// 查询关联单号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Hashtable GetItemRefOrderNo(string refOrderNo)
        {
            List<String> autoComplateList = new List<string>();
            Hashtable result = new Hashtable();

            try
            {
                List<MesWorkOrder> dt = service.GetWorkOrderInfo(refOrderNo);
                for (int i = 0; i < dt.Count; i++)
                {
                    result.Add(dt[i].Ruid.ToString(), dt[i].OrderNo.ToString());

                }
            }
            catch (Exception e)
            {
                result = new Hashtable();
            }
            return result;
        }


        #endregion






        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult EditMovementManage(String warehouseId)
        {

            ViewData.Add("editType", "new");

            List<KeyValueResult> menuList = this.service.getSelectWarehouse();
            if (menuList.Count > 0)
            {   //源仓库 目标仓库绑定默认值
                ViewData.Add("srcWarehouseId", menuList[0].value);
                ViewData.Add("destWarehouseId", menuList[0].value);
            }

            return View("EditMovementManage");
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult onClose(String orderNos)
        {
            bool flag = true;
            try
            {
                string empId = CurrentEmp.EmpId.ToString();
                flag = this.service.onClose(orderNos, empId);
            }
            catch (Exception e)
            {
                flag = false;
            }
            Hashtable result = new Hashtable();
            result.Add("status", flag);
            return Json(result);
        }

        /// <summary>
        /// 启用
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult onEnable(String orderNos)
        {
            bool flag = true;
            try
            {
                flag = this.service.EnableData(orderNos);
            }
            catch (Exception e)
            {
                flag = false;
            }
            Hashtable result = new Hashtable();
            result.Add("status", flag);
            return Json(result);
        }

        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult onDisable(String orderNos)
        {
            bool flag = true;
            try
            {
                flag = this.service.DisableData(orderNos);
            }
            catch (Exception e)
            {
                flag = false;
            }
            Hashtable result = new Hashtable();
            result.Add("status", flag);
            return Json(result);
        }
    }
}
